package com.rst.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.rst.model.MetaDataDTO;
import com.rst.model.TenantDTO;
import com.rst.model.TenantConfigMappingDTO;


@Repository
@Transactional
public class TenantConfigDAO{

	@Autowired
	private SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	public List<MetaDataDTO> getMataDataList() {
		Session session = sessionFactory.getCurrentSession();
		//Criteria criteria = sessionFactory.getCurrentSession().createCriteria(MetaDataDTO.class);
		
	    String str = "FROM MetaDataDTO md ";
	    Query query = session.createQuery(str);
		return query.list();
	}

	public Long saveTenant(TenantDTO tenant) {
		return (Long) sessionFactory.getCurrentSession().save(tenant);
			
	}

	public Long saveMetaDataMappingDTO(TenantConfigMappingDTO metaDataMapping) {
		 return (Long) sessionFactory.getCurrentSession().save(metaDataMapping);		
	}

	@SuppressWarnings("unchecked")
	public List<TenantDTO> getTenantList() {
		Session session = sessionFactory.getCurrentSession();
	    String str = "FROM TenantDTO td WHERE td.status = :status";
	    Query query = session.createQuery(str);
	    query.setParameter("status",  TenantDTO.ACTIVE);
	    return query.list(); 
	}

	public Long saveMetaData(MetaDataDTO metaData) {
		return (Long) sessionFactory.getCurrentSession().save(metaData);		
	}

	public String getLastTenantId() {
		Session session = sessionFactory.getCurrentSession();
		// session.setFlushMode(FlushMode.MANUAL);
		StringBuilder queryStr = new StringBuilder("select f_tenant_id from  t_tenant order by f_id desc limit 1 ");
		Query query = session.createSQLQuery(queryStr.toString());
		return (String) query.uniqueResult();
	}

	public TenantDTO getTenanatById(Long tenantId) {
		Session session = sessionFactory.getCurrentSession();
	    String str = "FROM TenantDTO td WHERE td.id = :tenantId AND td.status = :status";
	    Query query = session.createQuery(str);
	    query.setParameter("status",  TenantDTO.ACTIVE);
	    query.setParameter("tenantId",  tenantId);
		return (TenantDTO) query.uniqueResult();
	}

	public TenantConfigMappingDTO getXmlByTenantId(String tenantId) {
		Session session = sessionFactory.getCurrentSession();
	    String str = "FROM TenantConfigMappingDTO td WHERE td.tenantId = :tenantId";
	    Query query = session.createQuery(str);
	    query.setParameter("tenantId",  tenantId);
		return (TenantConfigMappingDTO) query.uniqueResult();
	}
	
}
